const KoaRouter = require('koa-router');
const router = new KoaRouter();
const Models = require('../models/index.js');
const Sequelize = require('sequelize');
const md5 = require('md5');

router.get('/', async ctx => {
    // 操作数据库
    // 找到用户 id 为 1 的用户，并找出他所有的评论
    // let datas = await Models.Users.findByPk(1, {
    //     include: {
    //         model: Models.Comments
    //     }
    // });

    // 获取 queryString 传递过来的数据
    let page = ctx.query.page || 1; // 当前页数
    let prepage = 2; // 每页条数
    let offset = (page - 1) * prepage; // 偏移量

    let result = await Models.Contents.findAndCountAll({
        limit: 2,
        offset,
        include: {
            model: Models.Users
        }
    });

    data = result.rows.map(v => {
        return {
            id: v.id,
            title: v.title,
            content: v.content,
            user_id: v.user_id,
            username: v.User.username,
            created_at: v.createdAt,
            like_count: v.like_count,
            comment_count: v.comment_count,
        }
    });

    ctx.body = {
        code: 0,
        prepage,
        count: result.count,
        data
    };
});

router.post('/register', async ctx => {
    // console.log(ctx.request.body);
    let username = ctx.request.body.username.trim();
    let password = ctx.request.body.password.trim();
    let repassword = ctx.request.body.repassword.trim();

    if (username == '' || password == '' || repassword == '') {
        return ctx.body = {
            code: 1,
            data: '用户名或密码不能为空'
        }
    }
    if (password != repassword) {
        return ctx.body = {
            code: 2,
            data: '用户名输入的密码不一致'
        }
    }

    let user = await Models.Users.findOne({
        where: {
            username
        }
    });

    if (user !== null) {
        return ctx.body = {
            code: 3,
            data: '当前用户已经被注册'
        }
    }

    let newUser = await Models.Users.build({
        username,
        password: md5(password)
    }).save();

    ctx.body = {
        code: 0,
        data: {
            id: newUser.id,
            username: newUser.username
        }
    }
});

router.post('/login', async ctx => {
    // console.log(ctx.request.body);
    let username = ctx.request.body.username.trim();
    let password = ctx.request.body.password.trim();

    let user = await Models.Users.findOne({
        where: {
            username
        }
    });

    if (user === null) {
        return ctx.body = {
            code: 1,
            data: '不存在该用户'
        }
    }

    if (user.get('password') !== md5(password)) {
        return ctx.body = {
            code: 1,
            data: '密码错误'
        }
    }

    // // 设置cookie
    // ctx.cookies.set('uid', user.get('id'), {
    //     // httpOnly：表示当前设置的cookie是否允许客户端进行操作（js）
    //     // 默认true，表示这个cookie能用于http协议的数据传输，但不允许js操作和篡改
    //     httpOnly: true,
    //     signed: true,
    //     // maxAge: 10000, // cookie 存活时间（毫秒为单位）
    // });
    // uid用下面的session存，username没那么重要，可以用cookie
    ctx.cookies.set('username', new Buffer(user.get('username')).toString('base64'), {
        httpOnly: false,
        signed: true,
        // maxAge: 10000,
    });
    // uid用session存
    ctx.session.uid = user.get('id');

    ctx.body = {
        code: 0,
        data: {
            id: user.get('id'),
            username: user.get('username')
        }
    }
});

router.post('/like', async ctx => {
    // 让客户端请求的时候带过来一个凭证
    // 要点赞的内容id
    let contentId = ctx.request.body.content_id;
    
    // 根据上面cookie确定，如果当前请求是一个登录的用户
    // 从cookie中读取uid
    let uid = ctx.session.uid;

    // console.log(contentId, uid);

    if (!uid) {
        return ctx.body = {
            code: 1,
            data: '你还没有登录',
        }
    }

    // 获取当前被点赞的内容（因为无法保证传递过来的content_id一定存在）
    let content = await Models.Contents.findByPk(contentId);
    // console.log(content);
    if (!content) {
        return ctx.body = {
            code: 2,
            data: '你要点赞的内容不存在或已删除'
        }
    }

    // 查询当前用户是否已对该内容点过赞
    let like = await Models.Likes.findOne({
        where: {
            [Sequelize.Op.and]: [
                {'content_id': contentId},
                {'user_id': uid}
            ]
        }
    });

    if (like) {
        return ctx.body = {
            code: 3,
            data: '你已经点过赞了'
        }
    }

    // 对内容的like数据进行增加
    content.set('like_count', content.get('like_count') + 1);
    await content.save();
    // console.log(content);

    // 再来更新likes详情表
    await Models.Likes.build({
        content_id: contentId,
        user_id: uid,
    }).save();

    ctx.body = {
        code: 0,
        data: content
    }
});

module.exports = router;